function initExperimentGroups(){
	$("#search_chromatograms").val("");
	$("#scdf_dialog").html("");
	//if (!isUpdate){
		//sample_group_regex = {};
		//sample_group_collection = {};
	//}
	$("#structure_span").html("");
	$("#experiment_archive").html("");
        $("#spectrum_form").hide();
        $("#spectrum_annotation_form").hide();
	$("#compound_form").hide();
	$("#exp_grps_form").show();	
}


function hideExperimentGroups(){
	//$("#exp_grps_form").hide();
	//$("#define_groups_form").hide();	
	myLayout.close('east');
}

function resetChrGrpForm(){
	$("#chrp_grp_association_div").html("");
}

function render_sgrp_html(){
	$("#define_groups_form").html('<span style="display:inline;padding-left: 10px;">Name&nbsp;&nbsp;</span><span style="display:inline;padding-left: 20px;">BioSample&nbsp;&nbsp;</span><span style="display:inline;padding-left: 20px;">OrgStrain&nbsp;&nbsp;</span><span style="display:inline;padding-left: 20px;">Type&nbsp;&nbsp;</span><span style="display:inline;padding-left: 30px;"><a href="#" class="atooltip" data-tip="see Daniel/Jake for RegularExp help">Regex&nbsp;&nbsp;</a></span><span style="display:inline;padding-left: 15px;">Description</span><br><tr><td style="width:60px;"><input id="sgrp_name0" style="width:60px;" onchange="updateSGName(\'0\')"></td><td style="width:80px;">&nbsp;<select id="sgrp_biosample0" style="width:80px;"></select><td style="width:100px;">&nbsp;<select id="sgrp_orgstrain0" style="width:100px;"></select></td><td style="width:70px;">&nbsp;<select id="sgrp_type0" style="width:70px;"></select></td><td style="width:60px;"><input id="sgrp_regex0" style="width:60px;"></td><td style="width:140px;">&nbsp;<input id="sgrp_desc0" style="width:80px;"></td></tr><br><tr><td style="width:60px;"><input id="sgrp_name1" style="width:60px;" onchange="updateSGName(\'1\')"></td><td style="width:80px;">&nbsp;<select id="sgrp_biosample1" style="width:80px;"></select><td style="width:100px;">&nbsp;<select id="sgrp_orgstrain1" style="width:100px;"></select></td><td style="width:70px;">&nbsp;<select id="sgrp_type1" style="width:70px;"></td><td style="width:60px;">&nbsp;<input id="sgrp_regex1" style="width:60px;"></td><td style="width:140px;">&nbsp;<input id="sgrp_desc1" style="width:80px;"></td></tr><br><tr><td style="width:60px;"><input id="sgrp_name2" style="width:60px;" onchange="updateSGName(\'2\')"></td><td style="width:80px;">&nbsp;<select id="sgrp_biosample2" style="width:80px;"></select><td style="width:100px;">&nbsp;<select id="sgrp_orgstrain2" style="width:100px;"></select></td><td style="width:70px;">&nbsp;<select id="sgrp_type2" style="width:70px;"></td><td style="width:60px;">&nbsp;<input id="sgrp_regex2" style="width:60px;"></td><td style="width:140px;">&nbsp;<input id="sgrp_desc2" style="width:80px;"></td></tr>');
}

function updateExperiment(eid){
	//sample_group_collection = {};
	//sample_group_regex = {};
	exp_group_num = 3;
	render_sgrp_html();
	$('#chr_grp_association_table').html("");
	active_experiment = eid;
	resetChrGrpForm();
	myLayout.open('east');
	$.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/get_experiment_details.cgi",
                	data: {'experiment_id': active_experiment},
                        success: function(json)
                        {
                        	if ($.parseJSON(json) == null){new Messi('Error on get_experiment_details.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
				var jo  = $.parseJSON(json);
				var experiment_groups = jo["aaData"];
				var chroms = jo["aaChroms"];
				var sample_groups = jo["aaSGroups"];
				existing_tracers = jo["tracers"];
				prepareExperimentGroups(experiment_groups, sample_groups, chroms, existing_tracers, function (){
					initExperimentGroups();
                			$("#experiment_group_status").html("");
					$("#isocheck").html("");
					$("#exp_add_form").show();
                			$("#experiment_form_message").html("Updating experiment: " + active_experiment + ' <a href="#" onclick="hideExperimentGroups();"><font color="red">Hide</font></a><br><a href="#" onclick="addExperiment();"><font size="-1" color="blue">Add New Experiment</font></a>');
					_updateExperiment = 1;
					$("#newExperimentButton").text("Update"); 
					$('#newGroupButton').attr("disabled", false);
                        		$('#chromGroupButton').attr("disabled", false);
					$('#searchChromatogramButton').attr("disabled", false);
					if (existing_tracers==null || existing_tracers.length == 0){
						$("#annotate_tracer").html('<br><a href="#" onclick="loadTracerForm();" class="atooltip" data-tip="Open form to set isotope tracer group relationships"><font color="blue">Stable isotope labeling?</font></a>');	
					}else{
						$("#annotate_tracer").html('');
					} 
					$("#experiment_archive").html('<button id="archiveExperimentButton" onClick="archiveExperiment()">Archive Experiment</button>');      
        			}
        			);
			},
                        error: function(){
                        	alert("Error retrieving experiment group details");
                        }
		});
}

function archiveExperiment(){
        new Messi('Are you sure you want to delete this experiment ' + $("#exp_title").val() + '?', {title: 'Archiving', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
                callback: function(val) { if (val == 'Y'){
                        $.ajax({
                        type: "POST",
                        url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                        data: { 'experiment_id': active_experiment, 'datatype':'experiment'},
                                success: function(json)
                                {
                                        $("#experiment_form_msg").html("Selected experiment archived " + $("#exp_title").val());
                                        hideExperimentGroups();
                                        new Messi('Experiment archived, refresh or do new search to update list. See Daniel/Jake to recover data', {title: 'Done', autoclose: 2000});
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
                }}});
}

function addExpProject(){
	$("#new_exp_project").css("display","inline");
}

function saveExpProject(){
	var new_project = $("#new_exp_project").val();
        new Messi('Save new project: ' + new_project,
                {title: 'Save new project?', buttons: [{id: 0, label: 'Add', val: 'Y'}, {id: 1, label: 'Cancel', val: 'C'}], unload: false,
                callback: function(val)
                {
                        if (val != "C"){
                       		var project_element = $("#exp_project");
				 $.ajax({
		                	type: "POST",
                			url:  "/cgi-bin/metabobase/update_experiment_groups.cgi",
                			data: {
                        			'project_name': new_project,
                			},
                			success: function(json)
                			{
						if ($.parseJSON(json) == null){new Messi('Error on update_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        			var jo  = $.parseJSON(json);
			 			project_element.append("<option value='" + jo["_new_proj_id"] + "' selected>" + new_project + "<option/>");
                        			$("#new_exp_project").val("");
						$("#new_exp_project").css("display", "none");
						$("#experiment_form_message").html("Experiment - new projected " + new_project + " added");
					},
					error: function(){
						alert("Error adding new project");
					}
				});
			}
                }
        });
}

function postExperimentGroups(){
	var expGrpObj = {};
	//var actualRows = 0;	
	expGrpObj["active_experiment"] = active_experiment;
	for (var i = 0; i < exp_group_num; i++){
		var _sgrpname = "#sgrp_name" + i;
		var _sgrpname_val = $(_sgrpname).val();
		if (_sgrpname_val != ""){
			expGrpObj["sgrp_name" + i] = _sgrpname_val;
			expGrpObj["sgrp_biosample" + i] = $("#sgrp_biosample" + i).val();
			expGrpObj["sgrp_orgstrain" + i] = $("#sgrp_orgstrain" + i).val();
			expGrpObj["sgrp_type" + i] = $("#sgrp_type" + i).val();
			expGrpObj["sgrp_regex" + i] = $("#sgrp_regex" + i).val();
			expGrpObj["sgrp_desc" + i] = $("#sgrp_desc" + i).val();
			expGrpObj["sgrp_actual_rows"] = "" + (i + 1);
			sample_group_regex[_sgrpname_val] = $("#sgrp_regex" + i).val();
			if (_updateExperiment == 1){
				if (sample_group_collection[_sgrpname_val] != null) 
					expGrpObj["sgrp_id" + i] = sample_group_collection[_sgrpname_val];
			}
		}else{
			//expGrpObj["sgrp_actual_rows"] = "" + (i + 1);
			break;
		}		
	}
	expGrpObj["exp_ops"] = "insert_exp_grps"; 
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/update_experiment_groups.cgi",
                data: expGrpObj, 
                success: function(json)
                {
			if ($.parseJSON(json) == null){new Messi('Error on update_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        var jo  = $.parseJSON(json);
                        new Messi('Experiment Groups Added/Updated', {titleClass:'success' ,title: 'Done', autoclose: 1200});
			$("#experiment_group_status").html("<font color='red'>Experiment groups saved</font>");
			exp_custom_groups = jo["_exp_grps"];
			cg_options = "";//add to global
			for (var ci = 0; ci< exp_custom_groups.length; ci++){
				cg_options = cg_options + '<option value = "' + exp_custom_groups[ci]["sample_group_id"] + '">' + exp_custom_groups[ci]["name"] + '</option>';
				sample_group_collection[exp_custom_groups[ci]["name"]] = exp_custom_groups[ci]["sample_group_id"];
			}
			active_group_html = cg_options + global_group_html;
			if ($('#tracer_groups').prop('checked')){
				$("#isotopic_tracer_form").html("");
				loadTracerForm();
			}
		},
                error: function(){
                        alert("Error adding new experiment groups");
                }
        });
}

function updateTracer(tgid){
	var labelfree_grp = $('#ntfd_grp'+tgid).val();
	if (labelfree_grp == tgid){
		new Messi('Label and label free groups can not be the same', {titleClass:'success' ,title: 'Error', autoclose: 2000});
		$('#ntfd_grp'+tgid).val("NA");
	}else{		
		$('#sample_tracer'+labelfree_grp).val("");
                $('#tracer_amount'+labelfree_grp).val("");	
	}
}

function validateTracerAmount(tgid){
        var amt = parseFloat($('#tracer_amount'+tgid).val());
	if (amt > 1 || amt <0){
                new Messi('Tracer amount must be between 0 and 1', {titleClass:'success' ,title: 'Error', autoclose: 2000});
                $('#tracer_amount'+labelfree_grp).val("");
        }
}

function loadTracerForm(){
	//for each group in exp_custom_groups ... associate each form element with group id, the preparation step, put tracer dropdown in hash
	var labeloptions = "";
	for (var ci = 0; ci< isotracer_list.length; ci++){
		labeloptions = labeloptions + '<option value = "' + isotracer_list[ci][0] + '">' + isotracer_list[ci][1] + ':' + isotracer_list[ci][2] + '</option>';
        }
        labeloptions = labeloptions + '<option value = "" selected></option>';
	$("#isotopic_tracer_form").append('<font color="cornflowerblue">Sample:Tracer</font><span><a href="#" title="Tracer and Amt from 1st group will be applied to all groups"  onclick="set2AllTracerGroups();"><font color="blue">&nbsp;set to all</font></a></font></span><span id="tracer_status"><font color="red">&nbsp;Adding</font></span><br>');
	var isoheader = "<tr><b><td style='width:50px;'>Group</td><td style='width:180px;'>Tracer</td><td style='width:100px;'><a class='atooltip' data-tip='Value needs to be 0 to 1 range for Percentages'>RelativeAmt %</a></td><td style='width:150px;'>NTFD Ref Group</td></tr></b>";
 	var isorows = "";
	var ntfd_cg_options = cg_options + '<option value = "NA" selected></option>'; 
	if (cg_options == ""){
        	for (var tg in exp_custom_groups){
			ntfd_cg_options = ntfd_cg_options +  '<option value = "' + exp_custom_groups[tg]["sample_group_id"] + '" >' + exp_custom_groups[tg]["name"] +  '</option>';
		}
	}
	for (var tg in exp_custom_groups){
		var tgid = exp_custom_groups[tg]["sample_group_id"];
		isorows = isorows + "<tr><td style='width:50px;'>" + exp_custom_groups[tg]["name"] + '</td>&nbsp;<td style="width:180px;"><select id="sample_tracer' + tgid + '" style="width:180px;">' + labeloptions +  '</select></td>&nbsp;<td style="width:100px;"><input type="number" value="1" style="width:100px;" min="0" max="1" size="10" id="tracer_amount' + tgid + '" ></td>&nbsp;<td style="width:150px;"><select id="ntfd_grp' + tgid + '" style="width:120px;" onchange="updateTracer(\'' + tgid + '\')">' + ntfd_cg_options +  '</select></td>' + '</tr>'; 
	}
	$("#isotopic_tracer_form").append(isoheader + isorows);
	$("#isotopic_tracer_form").append("<button id='groupTraceButton' onClick='postTracerGroups(\"insert_tracer_grps\")'>Save Tracers</button>");
}

function postTracerGroups(ops){
	var expGrpObj = {};
	var invalid = true;
        expGrpObj["active_experiment"] = active_experiment;
        for (var i = 0; i < exp_custom_groups.length; i++){
		var gid = exp_custom_groups[i]["sample_group_id"];
		expGrpObj["sample_group" + i] = gid;
        	expGrpObj["sample_tracer" + i] = $("#sample_tracer" + gid).val();
		if ($("#sample_tracer" + gid).val() != ""){
		    invalid = false;
		}
		var tva = $("#tracer_amount" + gid).val();
		if (tva == ""){
			tva = "NA";
		}
		expGrpObj["tracer_amount" + i] = tva;//$("#tracer_amount" + gid).val();
		expGrpObj["ntfd_grp" + i] = $("#ntfd_grp" + gid).val();
        }
	if (invalid == true){
	    new Messi('No labeling tracers selected', {title: 'Input error'});
	    return;
	}
	expGrpObj["tracer_rows"] = "" + i;
        expGrpObj["tracer_ops"] = ops;
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/update_tracer_groups.cgi",
                data: expGrpObj,
                success: function(json)
                {
                        if ($.parseJSON(json) == null){
				new Messi('Error on update_tracer_groups call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        var jo  = $.parseJSON(json);
                        new Messi('Tracer sample groups saved/updated', {titleClass:'success' ,title: 'Done', autoclose: 1800});
                        $("#tracer_status").html("<font color='red'>&nbsp;Saved/updated</font>");
                },
                error: function(){
                        alert("Error saving sample tracer groups");
                }
        });
}
function postChromGroups(){
        var grpChrObj = {};
        //var actualRows = 0;
	var incids = "";
        grpChrObj["active_experiment"] = active_experiment;
        grpChrObj["exp_ops"] = "insert_grp_chr";
	var newcgroups = "";
	//crows = crows + '<tr><td><a href="#" onclick="disassociateChromatogram(\'' + car[0] +'\',\'' +car[1] + '\',\'' + car[3] + '\');">Delete</a></td><td class="cgtd">' + car[3] + '&nbsp;&nbsp;' + car[4] + '</td></tr>';
	for (var chrid in active_sample_groups){
		var cpath = active_sample_groups[chrid];
		if ($("#group_" + chrid).val() != null){
                	incids = incids + chrid + ",";
			var _sgid = $("#group_" + chrid).val(); 
			grpChrObj["_grp_" + chrid] = _sgid; //$("#group_" + chrid).val();
			var sgname = "";
			for (var _sgn in sample_group_collection){
				if (sample_group_collection[_sgn] == _sgid){
					sgname = _sgn;
					break;
				}
			} 
		        //allchrs = allchrs + chrid + ":";	
			newcgroups = newcgroups + '<tr><td><a href="#" onclick="disassociateChromatogram(\'' + chrid +'\',\'' + $("#group_" + chrid).val() + '\',\'' + cpath + '\');">Delete</a></td><td class="cgtd">' + cpath + '&nbsp;&nbsp;' + sgname + '</td></tr>';
		}
        }
	grpChrObj["_grp_chrids"] = incids;
	if (incids == ""){
		new Messi('No Sample Group associations Selected', {titleClass:'warning' ,title: 'Done', autoclose: 1500});
		return;
	}
        $.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/update_experiment_groups.cgi",
                data: grpChrObj,
                success: function(json)
                {
			if ($.parseJSON(json) == null){new Messi('Error on chrom update_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        var jo  = $.parseJSON(json);
                        if (jo["_error"] == null || jo["_error"].length == 0){
				new Messi('Sample Group associations Saved', {titleClass:'success' ,title: 'Done', autoclose: 1200});
                        	$("#experiment_form_message").html("Sample Groups associations saved to active experiment " + active_experiment + + "<a href='#' onclick='hideExperimentGroups();'><font color='red'>Hide</font></a>" );
                        	$("#scdf_dialog").html("Sample Group associations saved, search to add more");
				$("#chr_search_results").html("");
				$("#search_chromatograms").val("");
				$("#chr_grp_function").html("");
				$("#chr_grp_association_table").html("");
				if ($("#chr_existing_results").html() != undefined ){
					$("#chr_existing_results").append(newcgroups);
				}else{
					var results = "<div class='excsg'><table id='chr_existing_results'><tr><th>&nbsp;</th><th>Associated chromatogram_sample_group</th></tr><font size='-2'>";
                                        results = results + newcgroups + "</font></table></div>";
					/*var downloadall = "";
					if (allchrs.length > 1){
					  downloadall = '<a href="http://metabolomics.uni.lux/~dweindl/mddb/dl.php?chroms=' + allchrs.substring(0, allchrs.length -1) +'">DownloadAll</a>&nbsp;';
					} */   
                                        $("#chr_grp_association_existing").html("<b><font color='blue'>Existing associations</font></b>&nbsp;<br>" + results);
				}
		}else{
				new Messi('Error with sample Group associations saving, please tell jake/daniel', {titleClass:'warning' ,title: 'Error'});
			}
                },
                error: function(){
                        alert("Error adding new experiment groups");
                }
        });
}


function postNewExperiment(){
	var _project = $("#exp_project").val();
	var _title = $("#exp_title").val();
	var _people = $("#exp_people").val();
	var _date = $("#exp_date").val();
	var _keywords = $("#exp_keywords").val();
	var _description = $("#exp_description").val();
	var _ops = 'insert_experiment';
	var _active_experiment = -1;
	if (_updateExperiment == 1){
		_ops = 'update_experiment';		
		_active_experiment = active_experiment;
	}
	$.ajax({
        	type: "POST",
        	url:  "/cgi-bin/metabobase/update_experiment_groups.cgi",
                data: {
                	'exp_ops': _ops, 'active_experiment':_active_experiment, 'exp_people': _people, 'exp_title': _title,'exp_date': _date,'exp_keywords': _keywords,'exp_description': _description,'project_name': _project
                },
                success: function(json)
                {
                	if ($.parseJSON(json) == null){new Messi('Error on new experiment update_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
			var jo  = $.parseJSON(json);			
			new Messi('Experiment Added/Updated and set as active', {titleClass:'success' ,title: 'Done', autoclose: 1200});
			active_experiment = jo["_new_exp_id"];
			_updateExperiment = 1;	
			$("#experiment_form_message").html("Experiment id " + active_experiment + " title " + _title + " added/updated " + "<a href='#' onclick='hideExperimentGroups();'><font color='red'>Hide</font></a>" );
			$('#newGroupButton').attr("disabled", false);
			$('#chromGroupButton').attr("disabled", false);
			$('#searchChromatogramButton').attr("disabled", false);
                },
                error: function(){
                	alert("Error adding new project");
                }
	});
}

//on update/edit mode, will want to set value to form
function prepareExperimentGroups(egarray, sgarray, chromarray, tracers, callback){
	$("#chr_grp_association_existing").html("");
	
	$.ajax({
        	type: "POST",
                url:  "/cgi-bin/metabobase/prepare_experiment_groups.cgi",
                data: {
                	'search_input': "",
                },
                success: function(json)
                {
			if ($.parseJSON(json) == null){new Messi('Error on prepare_experiment_groups.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
			var jo  = $.parseJSON(json);
			var mb_projects = jo["projects"];	
			var project_element = $("#exp_project");
			project_element.html("");
                        for (var jkey in mb_projects){
                        	project_element.append($("<option/>").attr("value", mb_projects[jkey][0]).text(mb_projects[jkey][1]));
                        }
			var mb_people = jo["experimenters"];
                        var people_element = $("#exp_people");
                        people_element.html("");
                        for (var jkey in mb_people){
				mb_users[mb_people[jkey][2]] = mb_people[jkey][0]; 
                                people_element.append($("<option/>").attr("value", mb_people[jkey][0]).text(mb_people[jkey][1]));
                        }
			var mb_strains = jo["strains"];
	                var strain_element = $("#sgrp_orgstrain0");
			var strain_element1 = $("#sgrp_orgstrain1");
                        var strain_element2 = $("#sgrp_orgstrain2");
			strain_element.html("");
                        strain_element1.html("");
			strain_element2.html("");
			orgStrainOptions = "";			
			for (var jkey in mb_strains){
				orgStrainOptions = orgStrainOptions + '<option value = "' + mb_strains[jkey][0] + '">' + mb_strains[jkey][1] + '</option>';
                                strain_element.append($("<option/>").attr("value", mb_strains[jkey][0]).text(mb_strains[jkey][1]));
                       		strain_element1.append($("<option/>").attr("value", mb_strains[jkey][0]).text(mb_strains[jkey][1]));
				strain_element2.append($("<option/>").attr("value", mb_strains[jkey][0]).text(mb_strains[jkey][1]));
			}
			var mb_bio_sample = jo["bio_samples"];			
                        var bio_sample_element = $("#sgrp_biosample0");
			var bio_sample_element1 = $("#sgrp_biosample1");
			var bio_sample_element2 = $("#sgrp_biosample2");
			bio_sample_element.html("");
                        bio_sample_element1.html("");
                        bio_sample_element2.html("");			
			bioSampleTypeOptions = "";
                        for (var jkey in mb_bio_sample){
				bioSampleTypeOptions = bioSampleTypeOptions + '<option value = "' + mb_bio_sample[jkey][0] + '">' + mb_bio_sample[jkey][1] + '</option>';
                                bio_sample_element.append($("<option/>").attr("value", mb_bio_sample[jkey][0]).text(mb_bio_sample[jkey][1]));
                        	bio_sample_element1.append($("<option/>").attr("value", mb_bio_sample[jkey][0]).text(mb_bio_sample[jkey][1]));
				bio_sample_element2.append($("<option/>").attr("value", mb_bio_sample[jkey][0]).text(mb_bio_sample[jkey][1]));
			}

			var mb_sample_type = jo["sample_type"];
                        var sgrp_type_element = $("#sgrp_type0");
                        var sgrp_type_element1 = $("#sgrp_type1");
                        var sgrp_type_element2 = $("#sgrp_type2");
                        sgrp_type_element.html("");
                        sgrp_type_element1.html("");
                        sgrp_type_element2.html("");
                        sampleTypeOptions = "";
                        for (var jkey in mb_sample_type){
                                sampleTypeOptions = sampleTypeOptions + '<option value = "' + mb_sample_type[jkey][0] + '">' + mb_sample_type[jkey][1] + '</option>';
                                sgrp_type_element.append($("<option/>").attr("value", mb_sample_type[jkey][0]).text(mb_sample_type[jkey][1]));
				sgrp_type_element1.append($("<option/>").attr("value", mb_sample_type[jkey][0]).text(mb_sample_type[jkey][1]));
				sgrp_type_element2.append($("<option/>").attr("value", mb_sample_type[jkey][0]).text(mb_sample_type[jkey][1]));
                        }

			exp_global_groups = jo["sample_group_global"];
                        global_group_html = "";
			active_group_html = "";
			sample_group_regex = {};
			sample_group_collection = {};
			
			isotracer_list = jo["tracers"];
                        if (exp_global_groups != null){
				for (var i = 0; i< exp_global_groups.length; i++){
                        		global_group_html = global_group_html + '<option value = "' + exp_global_groups[i][0] + '">' + exp_global_groups[i][1] + '</option>';
					sample_group_collection[exp_global_groups[i][1]] = exp_global_groups[i][0];
                        		global_group_regex[exp_global_groups[i][1]] = exp_global_groups[i][2];
				}
			}
			//active_people get value
			if (active_user != null && active_user != ""){
				$("#exp_people").val(mb_users[active_user]);
			}else{
				$("#exp_people").val("");
			}
			$("#exp_date").val("");
			$("#exp_project").val("");
			$("#exp_title").val("");
			$("#exp_keywords").val("");
			$("#exp_description").val("");
			for (var gi = 0; gi < exp_group_num; gi++){
				$("#sgrp_name" + gi).val("");
				$("#sgrp_regex" + gi).val("");
				$("#sgrp_desc" + gi).val("");
			} 
			$("#chr_search_results").html("");
			if (egarray != null && egarray.length > 0){//button must take on update
				var grouprows = sgarray.length;
				var globalct = 0;
				var customarray = [];
				for (var gi = 0; gi < sgarray.length; gi++){
					var _expinst = sgarray[gi];
                                        if (sgarray[gi][7] == true){
						globalct = globalct + 1;
					}else{
						customarray.push(sgarray[gi]);
					}
					//var sg = {};
					//sg["sample_group_id"] = _expinst[0];
					//sg["name"] = _expinst[1];
					//exp_custom_groups.push(sg);
					sample_group_collection[_expinst[1]] = _expinst[0];
                                        sample_group_regex[_expinst[1]] = _expinst[5];
                                        //active_group_html = active_group_html + '<option value = "' + _expinst[0] + '">' + _expinst[1] + '</option>';
				}
				for (var s in sample_group_collection){
					active_group_html = active_group_html + '<option value = "' + sample_group_collection[s] + '">' + s + '</option>';
				}
				grouprows = grouprows - globalct;
				var _expinst = egarray[0];
				$("#exp_people").val(_expinst[1]);
				$("#exp_date").val(_expinst[2]);
				$("#exp_project").val(_expinst[3]);
				$("#exp_title").val(_expinst[4]);
				$("#exp_keywords").val(_expinst[5]);
				$("#exp_description").val(_expinst[6]);	
				if (grouprows > 3){					
					addMoreGroups(grouprows - 3);
				}
				exp_custom_groups = [];
				for (var gi = 0; gi < customarray.length; gi++){
					var _expinst = customarray[gi];
					$("#sgrp_name" + gi).val(_expinst[1]);
					$("#sgrp_biosample" + gi).val(_expinst[2]);
					$("#sgrp_orgstrain" + gi).val(_expinst[3]); 
					$("#sgrp_desc" + gi).val(_expinst[4]);
					$("#sgrp_regex" + gi).val(_expinst[5]);
					$("#sgrp_type" + gi).val(_expinst[6]);
					var sg = {};
                                        sg["sample_group_id"] = _expinst[0];
                                        sg["name"] = _expinst[1];
                                        exp_custom_groups.push(sg);
				}
				if (chromarray != null && chromarray.length > 0){
                        		chromatogram_groups = chromarray;
					var results = "<div class='excsg'><table id='chr_existing_results'><tr><th>&nbsp;</th><th>Associated chromatogram_sample_group</th></tr><font size='-2'>";
                        		var crows = "";
					var allchrs = "";
                        		for (var i = 0; i < chromarray.length; i++){
                                		var car = chromarray[i];
						allchrs = allchrs + car[0] + ":";
                                		crows = crows + '<tr><td><a href="#" onclick="disassociateChromatogram(\'' + car[0] +'\',\'' +car[1] + '\',\'' + car[3] + '\');">Delete</a></td><td class="cgtd">' + car[3] + '&nbsp;&nbsp;' + car[4] + '</td></tr>';
                        		}
                        		results = results + crows + "</font></table></div>";
					var downloadall = "";
                                        if (allchrs.length > 1){
                                          downloadall = '<a href="http://metabolomics.uni.lux/~dweindl/mddb/dl.php?chroms=' + allchrs.substring(0, allchrs.length -1) +'">DownloadAll</a>&nbsp;';
                                        }
                        		$("#chr_grp_association_existing").html("<b><font color='blue'>Existing associations</font></b>&nbsp;" + downloadall + "<br>" + results);
				}
				$("#isotopic_tracer_form").html("");
				if (tracers != null && tracers.length > 0){
					//$("#isotopic_tracer_form").html("");
					//select distinct(tracer_id), relative_tracer_amount, sample_group, label_free_group
                			 $("#isotopic_tracer_form").append('<br><font color="cornflowerblue">Sample:Tracer</font><span id="tracer_status"><font color="red">&nbsp;Existing</font></span><br>');
                 			var isoheader = "<tr><b><td style='width:50px;'>Group</td><td style='width:180px;'>Tracer</td><td style='width:100px;'><a class='atooltip' data-tip='Value needs to be 0 to 1 range for Percentages'>RelativeAmt %</a></td><td style='width:150px;'>NTFD Ref Group</td></tr></b>";
                			var isorows = "";
					for (var t in tracers){
                        			var tlabel = tracers[t][0];
                        			var tamount = tracers[t][1];
                        			var sgname = "";
						var ntfdname = "";
						for (var sg in sample_group_collection){
							if (sample_group_collection[sg] == tracers[t][2]){
								sgname = sg;
							}
							if (sample_group_collection[sg] == tracers[t][3]){
                                                                ntfdname = sg;
                                                        }
						}
                        			isorows = isorows + "<tr><td style='width:50px;'>" + sgname + '</td>&nbsp;<td style="width:180px;">' + tlabel +  '</td>&nbsp;<td style="width:100px;">'+ tamount + '</td>&nbsp;<td style="width:150px;">' + ntfdname +  '</td>' + '</tr>';

                			}
                			$("#isotopic_tracer_form").append(isoheader + isorows);
					$("#isotopic_tracer_form").append("<button id='resetTracerButton' onClick='resetTracerGroups()'>Reset Tracers</button>");
				}
			}
			callback(); 
		},
		error: function(){
			alert("Error with experiment preparation db calls");
		}
	});
}

function resetTracerGroups(){
	new Messi('Are you sure you want to reset(permanently remove) all existing Tracer:Group:NTFD relationships?', {title: 'Tracer NTFD', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
                callback: function(val) { if (val == 'Y'){
			$("#isotopic_tracer_form").html("");	
			var expGrpObj = {};
			expGrpObj["tracer_ops"] = "delete_tracer_grps";
			var sample_group_ids = "";
			for (var i = 0; i < exp_custom_groups.length; i++){
                		sample_group_ids = sample_group_ids + "," + exp_custom_groups[i]["sample_group_id"];
			}
			sample_group_ids = sample_group_ids.substring(1,sample_group_ids.length);
			expGrpObj["sample_grps"] = sample_group_ids;
			$.ajax({
                	type: "POST",
                	url:  "/cgi-bin/metabobase/update_tracer_groups.cgi",
                	data: expGrpObj,
                	success: function(json)
                	{
                        	if ($.parseJSON(json) == null){
                                	new Messi('Error on update_tracer_groups call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                        	var jo  = $.parseJSON(json);
        			loadTracerForm();   
                        	$("#tracer_status").html("<font color='red'>&nbsp;Reset</font>");
                		new Messi('Isotopic tracers and labels reset completed. Please reassign as needed.', {title: 'Done', autoclose: 2000});
			},
                	error: function(){
                        	alert("Error resetting sample tracer groups, check with Jake/Daniel");
                	}
        		});		
		}
	}});
}

function refreshChromGroupTable(deletedCG){
	var results = "<div class='excsg'><table id='chr_existing_results'><tr><th>&nbsp;</th><th>Associated chromatogram_sample_group</th></tr><font size='-2'>";
        //var results = "<tr><th>&nbsp;</th><th>Associated chromatogram_sample_group</th></tr><font size='-2'>";
	var crows = "";
        for (var i = 0; i < chromatogram_groups.length; i++){
        	var car = chromatogram_groups[i];
		if (deletedCG == car[0]){
			chromatogram_groups.splice(i, 1);
			//continue;
		}else{
        		crows = crows + '<tr><td><a href="#" onclick="disassociateChromatogram(\'' + car[0] +'\',\'' +car[1] + '\',\'' + car[3] + '\');">Delete</a></td><td class="cgtd">' + car[3] + '&nbsp;&nbsp;' + car[4] + '</td></tr>';
        	}
	}
        results = results + crows + "</font></table></div>";
	$("#chr_grp_association_existing").html(results);
}

function disassociateChromatogram(cid, sid,cpath){
	new Messi('Are you sure you want to delete this chromatogram sample group: ' + cpath + '?', {title: 'Archiving', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
                callback: function(val) { if (val == 'Y'){
                        $.ajax({
                        type: "POST",
                        url:  "/cgi-bin/metabobase/archive_metabobase.cgi",
                        data: { 'experiment_id': active_experiment, 'chromatogram_id':cid, 'sample_group_id':sid, 'datatype':'chromatogram_sample_group'},
                                success: function(json)
                                {
                                        $("#experiment_form_msg").html("Selected chromatogram association deleted " + cpath);
					$("#scdf_dialog").html("Selected chromatogram association deleted " + cpath);
					refreshChromGroupTable(cid);
                                },
                                error:function(xhr,err)
                                {
                                        alert("Failed post\nreadyState: "+xhr.readyState+"\nstatus: "+xhr.status + "\nresponseText: "+xhr.responseText);
                                }
                        });
                }}});
}

function addExperiment(){
	$("#chr_search_results").html("");
	$("#experiment_group_status").html("");
	_updateExperiment = 0;
	exp_group_num = 3;
	if ($('#isocheck').val() == ""){
		$('#isocheck').html('<input id="tracer_groups" value="tracer" type="checkbox">&nbsp;Isotopic Tracer&nbsp;');
	}
	$("#isotopic_tracer_form").html("");
	$('#newGroupButton').attr("disabled", true);
        $('#chromGroupButton').attr("disabled", true);
	//$('#searchChromatogramButton').attr("disabled", true);
	$("#newExperimentButton").text("Save");
	render_sgrp_html();
	myLayout.open('east');
	prepareExperimentGroups([], [], [], [], function (){
		initExperimentGroups();
		if (active_user != null)	
			$("#exp_people").val(active_user["user_id"]);
                d = new Date();
		$( "#exp_date" ).val(d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
		$("#experiment_form_message").html('Adding new experiment and sample group associations <a href="#" onclick="hideExperimentGroups();"><font color="red">Hide</font></a>');
		$("#exp_add_form").show();		
		}
	);
}

function addMoreGroups(increment){
	var max = exp_group_num + increment;
	for (var row_start = exp_group_num;row_start< max; row_start++){
		var sgrp_row = '<br><tr>'
                        +'<td style="width:60px;"><input id="sgrp_name' + row_start + '" style="width:60px;" onchange="updateSGName(\'' + row_start + '\')"></td>'
                        +'<td style="width:80px;">&nbsp;<select id="sgrp_biosample' + row_start + '" style="width:80px;">' + bioSampleTypeOptions + '</select>'
                        +'<td style="width:100px;">&nbsp;<select id="sgrp_orgstrain' + row_start + '"  style="width:100px;">' + orgStrainOptions + '</select>'
			+'<td style="width:70px;">&nbsp;<select id="sgrp_type' + row_start + '" style="width:70px;">' + sampleTypeOptions + '</select>'
			+'<td style="width:60px;"><input id="sgrp_regex' + row_start + '" style="width:60px;"></td>' 
                        +'<td style="width:80px;">&nbsp;<input id="sgrp_desc' + row_start + '" style="width:80px;"></td>'
                        +'</tr>';
		$("#define_groups_form").append(sgrp_row);
	}
	exp_group_num = row_start;
}

function defineGroups(){
        myLayout.open('east');
}

function removeAllChromatograms(){
	new Messi('Remove all selected chromatograms?', {title: 'Archiving', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}], callback: function(val) {
	if (val == 'Y'){  
	    $('#chr_grp_association_table').html("");
	    $('#chr_grp_function').html('Chromatogram selections removed.');
	    active_sample_groups = {};
	}
	}});
}

function addAllChromatograms(){
	var rows = ""; 
	if (active_group_html == ""){
                active_group_html = global_group_html;
        }
	for (var ci = 0; ci < chromatogram_results.length; ci++){
        	var car = chromatogram_results[ci];
		active_sample_groups["" + car[0]] = car[1];
		var crow = '<tr><td><a onclick="$(this).parents(\'tr\').remove(); return false;" href="#" >remove</a></td>' + '<td>' + car[1] + '</td><td> ' + '<select id="group_' + car[0] + '">' + active_group_html;
		var selected_group_html = processRegex(car[0], car[1]);
        	if (selected_group_html != ""){
                	crow = '<tr><td><a onclick="$(this).parents(\'tr\').remove(); return false;" href="#" >remove</a></td>' + '<td>' + car[1] + '</td><td> ' + '<select id="group_' + car[0] + '">' + selected_group_html;
        	}else{
                	var gunselected = 'value = "' + '1' + '"';
                	var gselected = 'value = "' + '1' + '" selected';
                	selected_group_html = active_group_html.replace(gunselected,gselected);
                	crow = '<tr><td><a onclick="$(this).parents(\'tr\').remove(); return false;" href="#" >remove</a></td>' + '<td>' + car[1] + '</td><td> ' + '<select id="group_' + car[0] + '">' + selected_group_html;
        	}
		$('#chr_grp_association_table').append(crow);
	}
	$('#chr_grp_function').html('<b>Selected Chromatogram&nbsp;</b><a href="#" onclick="removeAllChromatograms();">removeAll</a>');
}

function searchChromatograms(){
	var search_val = $("#search_chromatograms").val();
	if (search_val.length < 2){
	    new Messi('Please put in at least 3 characters to search for chromatograms', {title: 'Input error'});
	    return;
	}
	var unassigned = 'F';
	var _unassigned = $('#onlyunassigned').prop('checked');
	if (_unassigned == true){
		unassigned = 'T';
	}
	$("#scdf_dialog").html("<img src='images/demo_wait.gif' />");
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/search_chromatogram.cgi",
                data: {
                        'search_input': search_val,'only_unassigned':unassigned
                },
                success: function(json)
                {
			if ($.parseJSON(json) == null){new Messi('Error on search_chromatogram.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
			$("#chr_search_results").html("");
                        var results = "<div class='b'><table id='chr_intermediate_results'><tr><th>&nbsp;</th><th>Chromatogram Search Results <a href='#' onclick='addAllChromatograms();'>addAll</a></th></tr><font size='-2'>";	
			var jo  = $.parseJSON(json);
                        chromatogram_results = jo["aaData"];
			$("#scdf_dialog").html(chromatogram_results.length + " results found");
			var crows = "";
			for (var i = 0; i < chromatogram_results.length; i++){
				var car = chromatogram_results[i];
				crows = crows + '<tr><td><a href="#" onclick="selectChromatogram(\'' + car[0] +'\',\'' +car[1] + '\');">add</a></td><td class="cgtd">' + car[1] + '</td></tr>';
                	}               
			results = results + crows + "</font></table></div>";
			$("#chr_search_results").html(results);
		}
		,error: function(){
			alert("error");
		}
	});
}

function processRegex(cid, chrompath){
        var selected_group_html = "";
        for (var regi in sample_group_regex){
                var regex_val = sample_group_regex[regi];
                if (regex_val == ""){
			continue;
		}
		var regex_pattern = new RegExp(regex_val, "i");
                if (chrompath.match(regex_pattern) != null){
                        var options_name = regi;
                        var sample_group_id = sample_group_collection[regi];
                        var gunselected = 'value = "' + sample_group_id + '"';
                        var gselected = 'value = "' + sample_group_id + '" selected';
                        selected_group_html = active_group_html.replace(gunselected,gselected);
                        return selected_group_html;//break;
                }
        }
	for (var regi in global_group_regex){
                var regex_val = global_group_regex[regi];
                if (regex_val == ""){
                        continue;
                }
                var regex_pattern = new RegExp(regex_val, "i");
                if (chrompath.match(regex_pattern) != null){
                        var options_name = regi;
                        var sample_group_id = sample_group_collection[regi];
                        var gunselected = 'value = "' + sample_group_id + '"';
                        var gselected = 'value = "' + sample_group_id + '" selected';
                        selected_group_html = active_group_html.replace(gunselected,gselected);
                        return selected_group_html;//break;
                }
        }
	return selected_group_html;
}

function selectChromatogram(cid, chrompath){
	/*
	<tr>
                                <td class="cgtd"><a href="remove2">Remove</a></td>
                                <td class="cgtd">new_gcms/2013/msdchem20130117/1/data/GCMS 5975C_001.D</td>
       
                         <td class="cgtd"><select id="sample_grp0"><option value="MSTFA">sgrp_2</option></select></td>
onclick="$(this).parents('tr').remove(); return false;" 
	var str = "Visit W3Schools";
var patt1 = /w3schools/i;
var patt2 = /ExM[WXY]/;
var str2 = "ExMW";
document.write(str.match(patt1));        
        </tr>*/
	if (active_group_html == ""){
		active_group_html = global_group_html;
	}
	var crow = '<tr><td><a onclick="$(this).parents(\'tr\').remove(); return false;" href="#" >remove</a></td>' + '<td>' + chrompath + '</td><td> ' + '<select id="group_' + cid + '">' + active_group_html; 
	var selected_group_html = processRegex(cid, chrompath);
	if (selected_group_html != ""){
		crow = '<tr><td><a onclick="$(this).parents(\'tr\').remove(); return false;" href="#" >remove</a></td>' + '<td>' + chrompath + '</td><td> ' + '<select id="group_' + cid + '">' + selected_group_html;
	}else{
		var gunselected = 'value = "' + '1' + '"';
                var gselected = 'value = "' + '1' + '" selected';
                selected_group_html = active_group_html.replace(gunselected,gselected);
		crow = '<tr><td><a onclick="$(this).parents(\'tr\').remove(); return false;" href="#" >remove</a></td>' + '<td>' + chrompath + '</td><td> ' + '<select id="group_' + cid + '">' + selected_group_html;
	}
	active_sample_groups["" + cid] = chrompath;
	$('#chr_grp_association_table').append(crow);
	$('#chr_grp_function').html('<b>Selected Chromatogram&nbsp;</b><a href="#" onclick="removeAllChromatograms();">removeAll</a>'); 
}

/*$('a.redc').click(function(e) {
  e.preventDefault(); // don't follow the link
  $(this).closest('tr').remove(); // credits goes to MrKurt for use of closest()
});
*/

function updateSGName(nindex){
	var nameval = $("#sgrp_name"+ nindex).val();
	$("#sgrp_regex"+ nindex).val(nameval);
}
/* Formating function for row details 
function fnFormatExperimentDetails ( nTr )
{
	var aData = oTable.fnGetData( nTr );
	var eid = aData[7];
 	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_experiment_details.cgi",
                        data: {'experiment_id': eid},
                        success: function(json)
                        {
                                if ($.parseJSON(json) == null){new Messi('Error on get_experiment_details.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
                                var jo  = $.parseJSON(json);
                                var experiment_groups = jo["aaData"];
                                var chroms = jo["aaChroms"];
                                var sample_groups = jo["aaSGroups"];
				var sOut = '<table cellpadding="1" cellspacing="0" border="0" style="padding-left:1px;">';
                sOut += '<tr><td><a href="javascript:tagExperiment(\''+ aData[7] +'\')"><img src="images/pin.png"/></a>' +
                '&nbsp; &nbsp;&nbsp;&nbsp;<a href="javascript:updateExperiment(\''+ aData[7] +'\')"><img src="images/pencil.png"/></a>' + '</td></tr>';
                sOut += '<tr><td>' + 'Short Description' +'</td></tr>';
                sOut += '<tr><td>' + 'Long Description' +'</td></tr>';
                sOut += '<tr><td><table><tr><th>' + 'chromatogram group organism tissue' +'</th></tr></table></td></tr>';
    sOut += '</table>';
    return sOut;
			},
                        error: function(){
                                alert("Error retrieving experiment group details");
                        }
                });
}
*/

var stayclose = false;
var eeid = 0;
var openids = {};
function setupExperimentDetails(eid){
            /*var nCloneTh = document.createElement( 'th' );
            var nCloneTd = document.createElement( 'td' );
            //nCloneTd.innerHTML = '<img src="images/details_open.png">';
	nCloneTd.innerHTML = '<img src="images/in_icon.png">';	
            nCloneTd.className = "center";*/
	/*if (oTable != null){
                                                    oTable.find('tr').each(function() {
                                                    var tr_element = jQuery(this);
                                                    tr_element.unbind('click.datatable_onTableRedraw');
                                                    });
                                                }
*/

    //$('#exp_metabo_tbl tbody td img').on('click', function () {
        var nTr = oTable.find("tr:contains('" + eid + "')")[0];//$(this).parents('tr')[0];
	var aData = oTable.fnGetData( nTr );
        //var eid = aData[7];
	detailsopen = false;
        if ( oTable.fnIsOpen(nTr) )
        {
            /* This row is already open - close it */
	    //this.src = "images/in_icon.png";
	    //this.parent.src = "images/in_icon.png";
	    $("#eid"+eid).attr("src","images/in_icon.png");
	    oTable.fnClose( nTr );
	    active_experiment_details = {};
	    detailsopen = true;
	    stayclose = true;
	    openids[eid] = undefined;
        }else{
            /* Open this row */
            //this.src = "images/details_close.png";
	//if (openids[eid] != undefined && openids[eid]== 1){
	//    return;
	//}
	//this.src = "images/out_icon.png";
	//this.parent.src = "images/out_icon.png";
	$("#eid"+eid).attr("src","images/out_icon.png");
	$.ajax({
                type: "POST",
                url:  "/cgi-bin/metabobase/get_experiment_details.cgi",
                        data: {'experiment_id': eid},
                        success: function(json)
                        {

                                if ($.parseJSON(json) == null){new Messi('Error on get_experiment_details.cgi call, please inform Daniel/Jake with work sequence. Refresh page', {title: 'Server error'});}
				//eeid = eid;
				openids[eid] = 1; 
			  	var jo  = $.parseJSON(json);
                                var experiment = jo["aaData"][0];
                                var chromarray = jo["aaChroms"];
                                var sample_groups = jo["aaSGroups"];
				var tracers = jo["tracers"];
 				var _groups = {};
				for (var sg in sample_groups){
					var sga = sample_groups[sg];
					_groups[sga[0]] = sample_groups[sg];
				}
                                var sOut = '<table cellpadding="1" cellspacing="0" border="0" style="padding-left:1px;">';
                		sOut += '<tr><td><a href="javascript:tagExperiment(\''+ aData[7] +'\')"><img src="images/pin.png"/></a>&nbsp;&nbsp;&nbsp;' +
                		' <a href="javascript:updateExperiment(\''+ aData[7] +'\')"><img src="images/pencil.png"/></a>' + '</td></tr>';
                		sOut += '<tr><td>' + 'Descriptions: ' + experiment[5] + '</td></tr>';
                		sOut += '<tr><td>' + experiment[6] +'</td></tr>';
				var crows = ""; 
				if (chromarray != null && chromarray.length > 0){
					sOut += '<tr><td><table><tr><th>chromatogram</th><th>group</th><th>biosample</th><th>organism-strain</th><th>method</th></tr>';
                                        chromatogram_groups = chromarray;
                                        for (var i = 0; i < chromarray.length; i++){
                                                var car = chromarray[i];
						var sgoa = _groups[car[1]];
						var gf = car[4];
						var biosample = biosample_dictionary[car[6]];
						var organism = organism_dictionary[sgoa[2]] + "-" + car[7];
						var cmethod = car[8];
						if (car[5] == true){
							gf = "<font color='green'>" + gf + "</font>";
							biosample = "-";
							organism = "-";
						}
                                                crows = crows + '<tr><td>' + car[3] + '</td><td>' + gf + '</td><td>' + biosample + '</td><td>' + organism + ' </td><td>' + cmethod +  '</td></tr>';
                                        }
					sOut += crows + '</table></table>';
                                }else{
					sOut += '<tr><td>There are zero associated sample groups and chromatograms</td></tr></table>'
				}
				oTable.fnOpen( nTr, sOut, 'details_exp' );
				active_experiment_details["experiment"] = experiment;
				active_experiment_details["chromarray"] = chromarray;
				active_experiment_details["sample_groups"] = sample_groups; 
                        },
                        error: function(){
                                alert("Error retrieving experiment group details");
                        }
                });
        }
    //} );
}

function tagExperiment(eid){
	var experiment = active_experiment_details["experiment"];
        var chromarray = active_experiment_details["chromarray"];;
        var sample_groups = active_experiment_details["sample_groups"];;
        var _groups = {};
        for (var sg in sample_groups){
		var sga = sample_groups[sg];
                _groups[sga[0]] = sample_groups[sg];
        }
        var sOut = '<table cellpadding="0" cellspacing="0" border="1" bordercolor="red" width="100%" style="padding-left:0px;">';
        sOut += '<tr><td><b><font color="blue">' + experiment[4] + ' date: ' + experiment[2] + ' contact: ' + experiment[16] + '</font></b></td></tr>';
        sOut += '<tr><td>' + 'Descriptions: ' + experiment[5] + '</td></tr>';
        sOut += '<tr><td>' + experiment[6] +'</td></tr>';
        var crows = "";
        if (chromarray != null && chromarray.length > 0){
        	sOut += '<tr><td><table><tr><th>chromatogram</th><th>sample group</th><th>biosample</th><th>organism</th></tr>';
                chromatogram_groups = chromarray;
                for (var i = 0; i < chromarray.length; i++){
                	var car = chromarray[i];
                        var sgoa = _groups[car[1]];
                        var gf = car[4];
                        if (car[5] == true){
                        	gf = "<font color='green'>" + gf + "</font>"
                        }
                        crows = crows + '<tr><td>' + car[3] + '</td><td>' + gf + '</td><td>' + biosample_dictionary[sgoa[2]] + '</td><td>' + organism_dictionary[sgoa[2]] + ' </td></tr>';
                }
                sOut += crows + '</table></table>';
         }else{
			sOut += '<tr><td>There are zero associated sample groups and chromatograms</td></tr></table>'
         }
	$("#exp_tagged_tbl").append(sOut + "<tr></tr>");
	//"<br>" + eid + " retrieve sample group and chromotagrams<br>");
}

function clearTaggedExperiments(){
	new Messi('Are you sure you want to clear all the pinned experiments?', {title: 'Clearing Pins', buttons: [{id: 0, label: 'Yes', val: 'Y'}, {id: 1, label: 'No', val: 'N'}],
                callback: function(val) { if (val == 'Y'){	
				$("#exp_tagged_tbl").html("");
			}
		}
	});
}

/*
Applying biosample and orgstrain selection from row 1 to all other rows
*/
function set2AllGroups(){
	var bio0 = $("#sgrp_biosample0").val();
	var orgstrain0 = $("#sgrp_orgstrain0").val();
	var sampletype0 = $("#sgrp_type0").val();
	for (var i = 1; i < exp_group_num; i++){
                $("#sgrp_biosample" + i).val(bio0);
                $("#sgrp_orgstrain" + i).val(orgstrain0);
        	$("#sgrp_type" + i).val(sampletype0);
	}
	$("#sgrp_biosample0").focus();
}

function set2AllTracerGroups(){
	var i = 0;
	var tracer = "";//$("#sgrp_biosample0").val();
        var relamt = "";//$("#sgrp_orgstrain0").val();
        var ortgid = "";
	for (var tg in exp_custom_groups){
		var tgid = exp_custom_groups[tg]["sample_group_id"];
                if (i == 0){
			//var tgid = exp_custom_groups[tg]["sample_group_id"];
			tracer = $("#sample_tracer" + tgid).val();
        		relamt = $("#tracer_amount" + tgid).val();
			ortgid = tgid;
		}else{
		 	$("#sample_tracer" + tgid).val(tracer);
                        $("#tracer_amount" + tgid).val(relamt);	
		}
		i = i + 1;
	}
	$("#sample_tracer" + ortgid).focus();
}

